<!DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>能力树</title>
    <!-- 添加 ECharts CDN -->
    <script src="echarts.min.js"></script>
    <style>
        body {
            margin: 0;
            padding: 0;
            width: 100%;
            max-width: 375px;
            margin: 0 auto;
        }

        @media screen and (max-width: 375px) {
            body {
                max-width: 100vw;
            }
        }

        .header-img {
            width: 100%;
        }

        .user-info {
            position: absolute;
            top: 300px;
            left: 50%;
            transform: translateX(-50%);
            z-index: 1;
            color: #fff;
            text-shadow: 0 1px 2px rgba(0, 0, 0, 1);
            text-align: center;
        }

        .user-name {
            font-size: 18px;
            font-weight: bold;
            margin-bottom: 5px;
        }

        .user-grade {
            font-size: 18px;
            font-weight: bold;
        }

        .user-label {
            color: #fff;
            margin-right: 5px;
        }

        .power-container {}

        .power-group {
            border: 1px solid #eee;
            margin: 5px 0;
            position: relative;
            width: 100%;
            aspect-ratio: 375/812;
            padding: 20px;
            box-sizing: border-box;
            background-image: url('https://qiniu.jingzhuzhixing.cn/xiaochengxu/ReportHTML/power-bg.png');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .power-group-header {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 0 5px;
            font-size: 12px;
            color: #666;
        }

        .power-group-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 40px;
            margin-bottom: 0;
        }

        .power-group-description {
            margin: 10px auto 15px;
            padding: 12px 15px;
            background: rgba(255, 255, 255, 0.9);
            border-radius: 8px;
            font-size: 13px;
            color: #666;
            line-height: 1.6;
            max-width: 90%;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
        }

        .color-block {
            width: 12px;
            height: 12px;
            margin-right: 8px;
            border-radius: 2px;
        }

        .sub-powers {
            margin-top: 30px;
            display: flex;
            flex-direction: column;
            gap: 15px;
            height: calc(100% - 100px);
            /* 减去标题和页眉的高度 */
        }

        .sub-power-item {
            display: flex;
            flex-direction: column;
            padding: 15px;
            background: #f8f8f8;
            border-radius: 8px;
            position: relative;
            flex: 1;
        }

        .sub-power-header {
            display: flex;
            align-items: center;
            position: relative;
        }

        .sub-power-name {
            flex: 1;
            font-size: 14px;
            color: #333;
            margin-left: 15px;
        }

        .sub-power-score {
            font-size: 14px;
            font-weight: bold;
            color: #666;
            margin-left: 10px;
            display: flex;
            align-items: center;
            gap: 2px;
        }

        .sub-power-description {
            margin-top: 10px;
            font-size: 12px;
            color: #666;
            line-height: 1.5;
            padding-left: 15px;
        }

        .sub-power-item::before {
            content: '';
            position: absolute;
            left: 0;
            top: 10px;
            width: 4px;
            height: 30px;
            background: #3498DB;
            border-radius: 2px;
        }

        .star {
            color: #FFD700;
            font-size: 16px;
        }

        .star-empty {
            color: #E0E0E0;
            font-size: 16px;
        }

        #radarContainer {
            width: 100%;
            height: 400px;
            position: relative;
            border: 1px solid #eee;
            padding: 20px;
            box-sizing: border-box;
            background-image: url('https://qiniu.jingzhuzhixing.cn/xiaochengxu/ReportHTML/power-bg.png');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .radar-header {
            position: absolute;
            top: 10px;
            right: 10px;
            padding: 0 5px;
            font-size: 12px;
            color: #666;
        }

        .radar-title {
            font-size: 16px;
            font-weight: bold;
            color: #333;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-top: 40px;
            margin-bottom: 20px;
        }

        .radar-chart {
            width: 100%;
            height: calc(100% - 80px);
            margin-top: 20px;
        }

        .pie-charts-container {
            display: flex;
            flex-direction: column;
            gap: 0px;
        }

        .pie-chart-item {
            width: 100%;
            height: 300px;
            position: relative;
            border: 1px solid #eee;
            padding: 20px;
            box-sizing: border-box;
            background-image: url('https://qiniu.jingzhuzhixing.cn/xiaochengxu/ReportHTML/power-bg.png');
            background-size: cover;
            background-position: center;
            background-repeat: no-repeat;
        }

        .pie-chart-title {
            font-size: 14px;
            font-weight: bold;
            color: #333;
            text-align: center;
            margin-bottom: 10px;
        }

        .pie-chart {
            width: 100%;
            height: calc(100% - 30px);
        }

        @media screen and (max-width: 375px) {
            .pie-chart-item {
                width: 100%;
            }
        }
    </style>
</head>

<body>
    <main>
        <div class="user-info">
            <div class="user-name"></div>
            <div class="user-grade"></div>
        </div>
        <img class="header-img" src="https://qiniu.jingzhuzhixing.cn/xiaochengxu/ReportHTML/header.png">
        <div id="powerContainer" class="power-container"></div>
        <div id="radarContainer">
            <div class="radar-header">------机器人创客能力评测报告</div>
            <div class="radar-title">能力图谱</div>
            <div id="radarChart" class="radar-chart"></div>
        </div>
        <div id="pieChartsContainer" class="pie-charts-container"></div>
    </main>
    <script>
        // const baseUrl = "http://192.168.2.7:8081";
        const baseUrl = "https://jingzhuzhixing.cn/api";

        // 获取URL参数
        function getUrlParam (name) {
            const url = new URL(window.location.href);
            return url.searchParams.get(name);
        }

        // 获取报告数据
        async function getReportData (reportKey) {
            try {
                const response = await fetch(`${baseUrl}/teaching/xiaochengxuReport/getTestReport`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        reportKey: reportKey
                    })
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const res = await response.json();
                return res;
            } catch (error) {
                console.error('获取报告数据失败：', error);
                throw error;
            }
        }

        // 获取能力树数据
        async function getPowerTree () {
            try {
                const response = await fetch(`${baseUrl}/teaching/xiaochengxuTestPower/getTestPower`, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const res = await response.json();
                console.log('获取能力树原始数据：', res);

                // 转换为树状结构
                const buildTree = (items, parentId = '0') => {
                    return items
                        .filter(item => item.parentId === parentId)
                        .map(item => ({
                            ...item,
                            children: buildTree(items, item.key)
                        }));
                };

                const treeData = buildTree(res.result);
                console.log('转换后的树状结构：', treeData);
                return treeData;
            } catch (error) {
                console.error('获取能力树数据失败：', error);
                throw error;
            }
        }

        // 初始化雷达图
        function initRadarChart (data) {
            const chartDom = document.getElementById('radarChart');
            const myChart = echarts.init(chartDom);

            // 处理数据，使用能力组作为指标
            const indicators = [];
            const scores = [];

            data.forEach(group => {
                indicators.push({
                    name: group.title,
                    max: 5
                });
                scores.push(group.gotScore || 0);
            });

            const option = {
                radar: {
                    indicator: indicators,
                    radius: '75%',
                    splitNumber: 4,
                    axisName: {
                        color: '#000000',
                        fontSize: 14
                    },
                    splitArea: {
                        areaStyle: {
                            color: ['rgba(250,250,250,0.3)', 'rgba(200,200,200,0.3)']
                        }
                    }
                },
                series: [{
                    type: 'radar',
                    data: [{
                        value: scores,
                        name: '能力评分',
                        areaStyle: {
                            color: 'rgba(52, 152, 219, 0.6)'
                        },
                        lineStyle: {
                            color: '#3498DB',
                            width: 2
                        },
                        itemStyle: {
                            color: '#3498DB'
                        }
                    }]
                }]
            };

            myChart.setOption(option);

            // 响应式调整
            window.addEventListener('resize', function () {
                myChart.resize();
            });
        }

        // 预设颜色数组
        const colorArray = [
            '#FF6B6B', // 珊瑚红
            '#4ECDC4', // 薄荷绿
            '#45B7D1', // 天蓝色
            '#96CEB4', // 淡绿色
            '#FFEEAD', // 淡黄色
            '#D4A5A5', // 淡粉色
            '#9B59B6', // 紫色
            '#3498DB', // 蓝色
            '#E67E22', // 橙色
            '#2ECC71'  // 绿色
        ];

        // 初始化饼图
        function initPieCharts (data) {
            const container = document.getElementById('pieChartsContainer');

            data.forEach((group, groupIndex) => {
                if (!group.children || group.children.length === 0) return;

                const pieChartItem = document.createElement('div');
                pieChartItem.className = 'pie-chart-item';

                const title = document.createElement('div');
                title.className = 'pie-chart-title';
                title.textContent = group.title;

                const chartDiv = document.createElement('div');
                chartDiv.className = 'pie-chart';
                chartDiv.id = `pieChart${groupIndex}`;

                pieChartItem.appendChild(title);
                pieChartItem.appendChild(chartDiv);
                container.appendChild(pieChartItem);

                const pieChart = echarts.init(chartDiv);

                const pieData = group.children.map((item, index) => ({
                    name: item.title,
                    value: item.gotScore || 0
                }));

                const option = {
                    tooltip: {
                        trigger: 'item',
                        formatter: '{b}: {c}分'
                    },
                    series: [{
                        type: 'pie',
                        radius: ['40%', '70%'],
                        avoidLabelOverlap: true,
                        itemStyle: {
                            borderRadius: 10,
                            borderColor: '#fff',
                            borderWidth: 2
                        },
                        label: {
                            show: true,
                            formatter: '{b}\n{c}分',
                            fontSize: 12,
                            color: '#000'
                        },
                        emphasis: {
                            label: {
                                show: true,
                                fontSize: 14,
                                fontWeight: 'bold'
                            }
                        },
                        data: pieData.map((item, index) => ({
                            ...item,
                            itemStyle: {
                                color: colorArray[index % colorArray.length]
                            }
                        }))
                    }]
                };

                pieChart.setOption(option);

                // 响应式调整
                window.addEventListener('resize', function () {
                    pieChart.resize();
                });
            });
        }

        // 页面加载完成后执行
        document.addEventListener('DOMContentLoaded', init);

        // 初始化
        async function init () {
            try {
                // 获取reportKey参数
                const reportKey = getUrlParam('reportKey');
                if (!reportKey) {
                    alert('缺少reportKey参数！');
                    return;
                }

                // 获取报告数据
                const reportData = await getReportData(reportKey);
                reportData.result.reportValue = JSON.parse(reportData.result.reportValue);
                const questions = reportData.result.reportValue.questions;
                const grade = reportData.result.reportValue.grade;
                const nickName = reportData.result.reportValue.nickName;

                // 显示用户信息
                document.querySelector('.user-name').innerHTML = `<span class="user-label">姓名：</span>${nickName}`;
                document.querySelector('.user-grade').innerHTML = `<span class="user-label">年级：</span>${grade}`;

                //分析答题数据
                for (let i = 0; i < questions.length; i++) {
                    const question = questions[i];
                    const questionId = question.questionId;
                    const answer = question.answer;
                    const score = question.options[answer].star;
                    question.gotScore = score;
                }

                console.log('答题数据：', questions);

                const powerGroups = (await getPowerTree())[0].children;
                console.log('树状结构：', powerGroups);

                // 计算子能力得分
                powerGroups.forEach(group => {
                    if (group.children) {
                        group.children.forEach(subPower => {
                            // 找出属于该子能力的所有题目
                            const relatedQuestions = questions.filter(q => q.power === subPower.key);
                            if (relatedQuestions.length > 0) {
                                // 计算平均分
                                const totalScore = relatedQuestions.reduce((sum, q) => sum + q.gotScore, 0);
                                subPower.gotScore = totalScore / relatedQuestions.length;
                            } else {
                                subPower.gotScore = 0;
                            }
                        });

                        // 计算能力组得分
                        const subPowerScores = group.children.map(sp => sp.gotScore);
                        if (subPowerScores.length > 0) {
                            group.gotScore = subPowerScores.reduce((sum, score) => sum + score, 0) / subPowerScores.length;
                        } else {
                            group.gotScore = 0;
                        }
                    }
                });

                console.log('处理后的能力树数据：', powerGroups);

                // 初始化雷达图
                initRadarChart(powerGroups);

                // 初始化饼图
                initPieCharts(powerGroups);

                // 渲染树状结构
                const container = document.getElementById('powerContainer');
                powerGroups.forEach((item, index) => {
                    const nodeDiv = document.createElement('div');
                    nodeDiv.className = 'power-group';

                    const headerDiv = document.createElement('div');
                    headerDiv.className = 'power-group-header';
                    headerDiv.textContent = '------机器人创客能力评测报告';

                    const titleDiv = document.createElement('div');
                    titleDiv.className = 'power-group-title';

                    const colorBlock = document.createElement('div');
                    colorBlock.className = 'color-block';
                    const colorIndex = index % colorArray.length;
                    const currentColor = colorArray[colorIndex];
                    colorBlock.style.backgroundColor = currentColor;

                    // 为子能力项添加自定义样式
                    const style = document.createElement('style');
                    style.textContent = `
                        .power-group:nth-child(${index + 1}) .sub-power-item::before {
                            background-color: ${currentColor};
                        }
                    `;
                    document.head.appendChild(style);

                    titleDiv.appendChild(colorBlock);
                    titleDiv.appendChild(document.createTextNode(item.title));

                    // 创建子能力容器
                    const subPowersDiv = document.createElement('div');
                    subPowersDiv.className = 'sub-powers';

                    // 遍历子能力
                    if (item.children && item.children.length > 0) {
                        item.children.forEach(subItem => {
                            const subPowerDiv = document.createElement('div');
                            subPowerDiv.className = 'sub-power-item';

                            const headerDiv = document.createElement('div');
                            headerDiv.className = 'sub-power-header';

                            const nameDiv = document.createElement('div');
                            nameDiv.className = 'sub-power-name';
                            nameDiv.textContent = subItem.title;

                            const scoreDiv = document.createElement('div');
                            scoreDiv.className = 'sub-power-score';

                            if (subItem.score) {
                                scoreDiv.textContent = `${subItem.gotScore}分`;
                            } else {
                                const starCount = subItem.gotScore;

                                for (let i = 0; i < starCount; i++) {
                                    const star = document.createElement('span');
                                    star.className = 'star';
                                    star.textContent = '★';
                                    scoreDiv.appendChild(star);
                                }

                                for (let i = starCount; i < 5; i++) {
                                    const star = document.createElement('span');
                                    star.className = 'star-empty';
                                    star.textContent = '☆';
                                    scoreDiv.appendChild(star);
                                }
                            }

                            const descriptionDiv = document.createElement('div');
                            descriptionDiv.className = 'sub-power-description';
                            // 这里可以根据实际数据添加描述，暂时使用示例文本
                            descriptionDiv.textContent = subItem.value;

                            headerDiv.appendChild(nameDiv);
                            headerDiv.appendChild(scoreDiv);
                            subPowerDiv.appendChild(headerDiv);
                            subPowerDiv.appendChild(descriptionDiv);

                            subPowersDiv.appendChild(subPowerDiv);
                        });
                    }

                    nodeDiv.appendChild(headerDiv);
                    nodeDiv.appendChild(titleDiv);

                    // 添加能力组描述
                    if (item.value) {
                        const descriptionDiv = document.createElement('div');
                        descriptionDiv.className = 'power-group-description';
                        descriptionDiv.textContent = item.value;
                        nodeDiv.appendChild(descriptionDiv);
                    }

                    nodeDiv.appendChild(subPowersDiv);
                    container.appendChild(nodeDiv);
                });

            } catch (error) {
                console.error('初始化失败：', error);
            }
        }
    </script>
</body>

</html>